var mongoose = require('mongoose');

function merge (target, src) {
  const result = { ...target }
  Object.keys(target).forEach(key => {
    if (target.hasOwnProperty(key)) {
      result[key] = src[key]
    }
  })
  return result
}

function queryResolver (query) {
  const result = {}
  Object.keys(query).filter(key => key.indexOf('s_') > -1).forEach(queryKey => {
    result[queryKey.substring(2)] = new RegExp(query[queryKey], "i")
  })

  return result
}

function handleError (res, err) {
  res.json({ status: 'failure', data: err })
}

const isString = (obj) => {
  return Object.prototype.toString.apply(obj) === '[object String]'
}

const isArray = (obj) => {
  return Object.prototype.toString.apply(obj) === '[object Array]'
}

const isObject = (obj) => {
  return Object.prototype.toString.apply(obj) === '[object Object]'
}

const isValidObjectId = (id) => {
  //return mongoose.Types.ObjectId.isValid(id)
  return id.toString().match(/^[0-9a-fA-F]{24}$/)
}

const getExcelColumnLetter = (seq) => {
  const _seq = seq < 1 ? 1 : seq
  const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  return letters[_seq - 1]
}

const validateSchemaAttr = (attr) => {
  if('datasource' == attr.dtype) {
    if(!isObject(attr.datasource) || !attr.datasource.hasOwnProperty('url')) {
      return '数据源属性必须设置数据源地址';
    }
  } else if('enum' == attr.dtype) {
    if(!isArray(attr.enums) || attr.enums.length < 1) {
      return '枚举属性必须设置枚举项';
    }
  }  else if('foreign' == attr.dtype) {
    if(!isString(attr.dvalue)) {
      return '外键属性必须设置模型编码';
    }
  }

  return true;
}

module.exports = {
  merge,
  queryResolver,
  handleError,
  isArray,
  isObject,
  isValidObjectId,
  getExcelColumnLetter,
  validateSchemaAttr
}
